package db

import (
	"fmt"
	"gorm-demo/lib/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

var (
	db *gorm.DB
)

func createDB(username string, password string, host string, port int64, database string) *gorm.DB {
	//dsn := "gjf:123456@tcp(121.4.213.43:3306)/gjf?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database,
	)
	// 配置日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	_dbConnect, err := gorm.Open(
		mysql.Open(dsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // 禁用创建表名复数带 s
				TablePrefix:   "",   // 统一表前缀, 自定义表名会覆盖全局
			},
			//DisableForeignKeyConstraintWhenMigrating: true, // AutoMigrate 会自动创建数据库外键约束，您可以在初始化时禁用此功能
			Logger: newLogger,
		})
	if err != nil {
		panic("failed to connect database")
	}
	return _dbConnect
}

func init() {
	db = createDB(config.DB_W_username, config.DB_W_password, config.DB_W_host, config.DB_W_port, config.DB_W_database)
}

func GetDB() *gorm.DB {
	return db.Debug()
}
